package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialToken;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        //1、根据code换取token
        Map<String,String> headers = new HashMap<>();
        Map<String,String> querys = new HashMap<>();
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("grant_type","authorization_code");
        tokenMap.put("code",code);
        tokenMap.put("client_id","fc07ce03f0ded1f6433e7b7e96f445bb687e3c48853342391b22ab2f70d393d3");
        tokenMap.put("redirect_uri","http://auth.gulimall.com/oauth2.0/gitee/success");
        tokenMap.put("client_secret","3dbb839338ac5ac4138de3cd44daad8ff21d6329d3d2da8a356a1e4e2b948f40");
        HttpResponse tokenResponse = HttpUtils
                .doPost("https://gitee.com",
                        "/oauth/token",
                        "post",
                        headers,
                        querys,
                        tokenMap);

        if (tokenResponse.getStatusLine().getStatusCode() == 200){
            //获取到了token
            String tokenString = EntityUtils.toString(tokenResponse.getEntity());
            SocialToken socialToken = JSON.parseObject(tokenString, SocialToken.class);
            String access_token = socialToken.getAccess_token();
            querys.put("access_token",access_token);
            HttpResponse userResponse = HttpUtils
                    .doGet("https://gitee.com",
                            "/api/v5/user",
                            "get",
                            headers,
                            querys);
            if (userResponse.getStatusLine().getStatusCode()== 200){
                String userString = EntityUtils.toString(userResponse.getEntity());
                SocialUser socialUser = JSON.parseObject(userString, SocialUser.class);
                socialUser.setAccess_token(access_token);

                String expires_in = socialToken.getExpires_in();
                socialUser.setExpires_in(expires_in);
                R oauthLogin = memberFeignService.oauthLogin(socialUser);
                if (oauthLogin.getCode() == 0){
                    MemberRespVo data = oauthLogin.getData("data", new TypeReference<MemberRespVo>() {
                    });
                    //todo 1、默认发的令牌。session=？。作用域：当前域 （1.解决子域session共享问题）
                    //todo 2、用json的序列化对象存储到redis中
                    session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                    //1、第一次使用session，命令浏览器保存卡号。JSESSIONID这个cookie
                    //2、以后浏览器访问哪个网站就会带上这个网站的cookie
                    //子域之间：gulimall.com auth.gulimall.com order.gulimall.com
                    //发卡的时候（指定域名为父域名），即使是子域系统发的卡，也能让父域直接使用

                    return "redirect:http://gulimall.com";
                }else {
                    System.out.println("社交登录异常******************************");
                    return "redirect:http://auth.gulimall.com/login.html";
                }


                //知道当前是哪个社交用户
                //1）、当前用户如果是第一次进这个网站就自动注册进来
                // （为当前社交用户生成会员信息账号，以后这个社交账号就对应指定的会员）
                //登录或者注册这个社交用户
            }else {
                return "redirect:http://auth.gulimall.com/login.html";

            }


        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
